<?php

namespace app\v1\common\controller;

use app\common\model\LoginRecord;
use app\common\model\PayConfig;
use app\common\model\Recharge;
use app\common\model\RefundLog;
use app\common\model\User;
use Omnipay\Omnipay;
use think\Config;
use think\Controller;
use think\Db;
use think\Log;
use think\Request;
use JiaweiXS\WeApp\WeApp;

class UserController extends Controller
{
    public function __construct()
    {
        Config::load(APP_PATH . 'v1/common/config.php');
    }

    /**
     * @param Request $request
     * 获取用户信息
     */
    public function authUser(Request $request)
    {
        $code = $request->param('code');
        //创建一个小程序对象
        $weapp = new WeApp('wxc60aac65239987f1', 'c889d97b7f549059f96101898a215880', '/home/wwwroot/aution/runtime');
        //code 换取 session_key
        $data = $weapp->getSessionKey($code);

        return json(['code' => 200, 'info' => '已获取到数据', 'data' => json_decode($data, true)]);
    }


    /**
     * @return \think\response\Json
     * 登录或者首次登陆
     */
    public function login(Request $request)
    {
        $loginInfo['password']     = $request->param('password') ?: '';
        $loginInfo['isPhoneLogin'] = $request->param('isPhoneLogin') ?: 0;
        $loginInfo['mobile']       = $request->param('mobile');
        $loginInfo['open_id']      = $request->param('open_id');
        $loginInfo['photo']        = $request->param('photo');
        $loginInfo['name']         = $request->param('name');
        $loginInfo['sex']          = $request->param('sex') ?: 1;
        $data['platform']          = $request->param('platform') ?: 2;//1APP,2小程序,3微信公众号,4PC
        $data['mobile_system']     = $request->param('mobile_system') ?: '未知';//手机系统
        $data['mobile_model']      = $request->param('mobile_model') ?: '未知';//手机型号

        //手机登录
        if ($loginInfo['isPhoneLogin']) {

            $user_info = UserModel::where('mobile', $loginInfo['mobile'])->find();
            if (empty($user_info)) {
                return json(['code' => '404', 'info' => '该手机用户不存在']);
            }
            $user_real_password = $user_info->password;
            //验证密码
            if (verifyPassword($loginInfo['password'], $user_real_password)) {
                $user_info['grade'] = GradeModel::where('num', '<=', $user_info->integral)
                    ->order('num desc')->value('grade') ?: 0;
                //首次登陆加积分
                if (empty(LoginRecord::where(['user_id' => $user_info['id']])->find())) {
                    UserModel::where('id', $user_info['id'])->setInc('integral', 5);
                    Integral::create([
                        'user_id' => $user_info['id'],
                        'integral' => 5,
                        'task_name' => '首次登陆',
                        'task_id' => 11
                    ]);
                }
                $record['user_id'] = $user_info['id'];
                $record['type']    = 2;
                LoginRecord::create($record);

                UserModel::where('id', $user_info['id'])->update($data);

                return json(['code' => '200', 'info' => '登录成功', 'data' => changeNullFirst($user_info->toArray())]);
            } else {
                return json(['code' => '404', 'info' => '密码错误']);
            }
        } else {
            //open_id登录
            $user_info = User::where('open_id', $loginInfo['open_id'])->find();

            //有open_id
            if (!empty($user_info)) {
                User::where('id', $user_info['id'])->update([
                    'photo' => $loginInfo['photo'],
                    'open_id' => $loginInfo['open_id'],
                    'nickname' => $loginInfo['name'],
                    'sex' => $loginInfo['sex'],
                    'mobile_system' => $data['mobile_system'],
                    'platform' => $data['platform'],
                    'mobile_model' => $data['mobile_model'],
                ]);
                $record['user_id'] = $user_info['id'];
                $record['type']    = 1;
                LoginRecord::create($record);
                $user_data = User::where(['id' => $user_info['id']])->field([
                    'id',
                    'open_id',
                    'photo',
                    'nickname',
                    'sex',
                    'coin',
                ])->find();
                return json(['code' => 200, 'info' => '登录成功', 'data' => $user_data]);
            } else {
                //直接创建
                $data_crate_by_wechat['open_id']       = $loginInfo['open_id'];
                $data_crate_by_wechat['photo']         = $loginInfo['photo'];
                $data_crate_by_wechat['nickname']      = $loginInfo['name'];
                $data_crate_by_wechat['username']      = $loginInfo['name'];
                $data_crate_by_wechat['sex']           = $loginInfo['sex'];
                $data_crate_by_wechat['mobile_system'] = $data['mobile_system'];
                $data_crate_by_wechat['platform']      = $data['platform'];
                $data_crate_by_wechat['mobile_model']  = $data['mobile_model'];
                $res_create                            = User::create($data_crate_by_wechat);
                if ($res_create) {
                    $record['user_id'] = $res_create['id'];
                    $record['type']    = 1;
                    LoginRecord::create($record);
                    $user_data = User::where(['id' => $res_create['id']])->field([
                        'id',
                        'open_id',
                        'photo',
                        'nickname',
                        'sex',
                        'coin',
                    ])->find();
                    return json(['code' => 200, 'info' => '创建成功', 'data' => $user_data]);
                } else {
                    return json(['code' => 500, 'info' => '注册失败']);
                }
            }
        }
    }


    /**
     * @param Request $request
     * @return \think\response\Json
     * 充值
     */
    public function recharge(Request $request)
    {
        $data['user_id']  = $request->param('user_id');
        $data['order_sn'] = get_order_sn();
        $data['account']  = $request->param('money');
        $data['pay_code'] = $request->param('pay_code') ?: 'weixin';

        $user_info = User::where(['id' => $data['user_id']])->find();

        if (empty($user_info)) {
            return json(['code' => 500, 'info' => '获取用户信息失败']);
        }
        $open_id = $user_info->open_id;


        if (Recharge::create($data)) {
            $gateway = Omnipay::create('WechatPay_Js');
            $gateway->setAppId('wxc60aac65239987f1');
            $gateway->setMchId('1219192901');
            $gateway->setApiKey('LTjSNFNA0d6PJa14r6NIM0pjv0m9CDoe');
            $gateway->setNotifyUrl('https://aution.jishuzai.top/v1/api/checkSignWechatMiniPay');

            $order = [
                'body' => 'The test order',
                'out_trade_no' => $data['order_sn'],
                'total_fee' => $data['account'] * 100, //=0.01
                'spbill_create_ip' => $request->ip(),
                'openid' => $open_id,
                'fee_type' => 'CNY',
            ];

            $request    = $gateway->purchase($order);
            $response   = $request->send();
            $is_success = $response->isSuccessful();
            if ($is_success) {
                return json(['code' => 200, 'info' => '已获取到数据', 'data' => $response->getJsOrderData()]);
            }
        }

        return json(['code' => 500, 'info' => '获取支付信息失败']);
    }

    /**
     * @param Request $request
     * 支付回调
     */
    public function checkSignWechatMiniPay(Request $request)
    {
        $gateway = Omnipay::create('WechatPay_Js');
        $gateway->setAppId('wxc60aac65239987f1');
        $gateway->setMchId('1219192901');
        $gateway->setApiKey('LTjSNFNA0d6PJa14r6NIM0pjv0m9CDoe');

        $response = $gateway->completePurchase([
            'request_params' => file_get_contents('php://input')
        ])->send();

        if ($response->isPaid()) {
            //pay success
            $result = $response->getRequestData();
            Log::error($response->getRequestData());
            $order = Recharge::where(['order_sn' => $result['out_trade_no']])->find();
            if (empty($order)) {
                return 'FAIL';
            }
            $pay_success = Recharge::where(['id' => $order['id']])->update([
                'pay_status' => 1,
                'pay_time' => time(),
                'transaction_id' => $result['transaction_id']
            ]);
            if ($pay_success) {
                $pay_config = PayConfig::get(1);
                $up_coin    = ($order['account'] * $pay_config['coin']) / $pay_config['coin_to_money'];
                //对应的加拍币和余额
                User::where(['id' => $order['user_id']])->setInc('coin', $up_coin);
                User::where(['id' => $order['user_id']])->setInc('balance', $order['account']);
                return 'SUCCESS';
            }
            return 'FAIL';
        } else {
            return 'FAIL';
        }
    }


    /**
     * @param Request $request
     * 编辑地址
     */
    public function addOrEditAddress(Request $request)
    {
        $user_id          = $request->param('user_id');
        $data['address']  = $request->param('address');
        $data['mobile']   = $request->param('telNumber');
        $data['username'] = $request->param('userName');

        if (User::where(['id' => $user_id])->update($data)) {
            return json(['code' => 200, 'info' => '保存成功']);
        }
        return json(['code' => 500, 'info' => '保存失败']);
    }


    /**
     * @param Request $request
     * @return \think\response\Json
     * 地址列表
     */
    public function addressList(Request $request)
    {
        $user_id = $request->param('user_id');
        $data    = User::where(['id' => $user_id])->field(['id as user_id', 'address'])->find();
        return json(['code' => 200, 'info' => '已获取到数据', 'data' => $data]);
    }


    /**
     * @param Request $request
     * 充值记录
     */
    public function rechargeLog(Request $request)
    {
        $user_id = $request->param('user_id');
        $limit   = $request->param('limit') ?: 10;
        $page    = $request->param('page') ?: 1;
        $data    = Recharge::where(['user_id' => $user_id])->paginate($limit, false, ['page' => $page]);
        return json(['code' => 200, 'info' => '已获取到数据', 'data' => $data]);
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * 用户钱包
     */
    public function userMoney(Request $request)
    {
        $user_id   = $request->param('user_id');
        $user_data = User::where(['id' => $user_id])->field([
            'id',
            'open_id',
            'photo',
            'nickname',
            'sex',
            'coin',
        ])->find();
        return json(['code' => 200, 'info' => 'success', 'data' => $user_data]);
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * 用户退币日志获取
     */
    public function userdrawBack(Request $request)
    {
        $user_id = $request->param('user_id');
        $page = $request->param('page') ?: 1;
        $limit = $request->param('limit') ?: 10;
        $res = Db::name('refund_log')
            ->alias('log')
            ->join('goods g','log.goods_id = g.goods_id')
            ->where(['log.user_id' => $user_id])
            ->field(['log.id'=>'id','log.user_id'=>'user_id','log.goods_id'=>'goods_id','log.refund_coin'=>'refund_coin','log.refund_money'=>'refund_money','log.create_time'=>'create_time','g.goods_name'=>'goods_name','g.detail_img'=>'deteil_img'])
            ->paginate($limit,false,['page'=>$page]);

        return json(['code'=>200, 'info' => 'success','data'=>$res]);
    }

}
